package com.sishu.njrtsdms.utils;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 分页构建工具
 */
public class PageUtils {
    /**
     * 当前记录起始索引
     */
    public static final String PAGE_NUM = "page";

    /**
     * 每页显示记录数
     */
    public static final String PAGE_SIZE = "pageSize";

    /**
     * 排序列
     */
    public static final String ORDER_BY_COLUMN = "orderByColumn";

    /**
     * 排序的方向 "desc" 或者 "asc".
     */
    private static final String DIRECTION_FLAG = "direction";

    private static final String ASC = "asc";

    private static final String DESC = "desc";

    /**
     * 封装分页对象
     */
    public static Pageable getPageable() {
        Integer pageNum = Convert.toInt(ServletUtils.getParameter(PAGE_NUM), 1);
        Integer pageSize = Convert.toInt(ServletUtils.getParameter(PAGE_SIZE), 10);
        String orderBy = ServletUtils.getParameter(ORDER_BY_COLUMN);
        if (StrUtil.isBlank(orderBy)) return PageRequest.of(pageNum, pageSize);

        String directionFlag = ObjUtil.defaultIfBlank(ServletUtils.getParameter(DIRECTION_FLAG),
                DESC);
        Sort.Direction direction = StrUtil.equalsIgnoreCase(directionFlag, ASC) ?
                Sort.Direction.ASC :
                Sort.Direction.DESC;
        Sort sort = Sort.by(direction, orderBy);
        return PageRequest.of(pageNum, pageSize, sort);
    }

    public static Pageable buildPageRequest() {
        return getPageable();
    }
}
